package ru.jexp.rcp.supply.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;

import ru.jexp.rcp.supply.img.JExpImageLink;
import ru.jexp.rcp.supply.mui.JExpSupplyMessages;

public class ActionDelete extends Action implements ISelectionListener,
		IPartListener {

	public static final String ID = "ru.jexp.rcp.supply.actions.actiondelete";

	private IDeleteCommand activePart;

	public ActionDelete(IWorkbenchWindow window) {
		setId(ID);
		setActionDefinitionId(ID);
		setText(JExpSupplyMessages.Delete_pattern_action_text);
		setToolTipText(JExpSupplyMessages.Delete_pattern_action_tooltip);
		setImageDescriptor(JExpImageLink
				.getImageDescriptor(JExpImageLink.DELETE));
		setEnabled(false);
		window.getSelectionService().addSelectionListener(this);
		window.getPartService().addPartListener(this);
	}

	@Override
	public void run() {
		activePart.delete();
	}

	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection selection) {
		setEnabled(activePart != null && activePart.canDelete());
	}

	@Override
	public void partActivated(IWorkbenchPart part) {
		if (part instanceof IDeleteCommand) {
			activePart = (IDeleteCommand) part;
		} else {
			activePart = null;
			setEnabled(false);
		}
	}

	@Override
	public void partBroughtToTop(IWorkbenchPart part) {
	}

	@Override
	public void partClosed(IWorkbenchPart part) {
		if (part instanceof IDeleteCommand) {
			if (activePart == part) {
				activePart = null;
				setEnabled(false);
			}

		}
	}

	@Override
	public void partDeactivated(IWorkbenchPart part) {
		setEnabled(false);
		activePart = null;
	}

	@Override
	public void partOpened(IWorkbenchPart part) {
	}

	public static boolean ShowMessageAcceptDelete(Shell shell) {
		return MessageDialog.openConfirm(shell,
				JExpSupplyMessages.Delete_messagebox_title,
				JExpSupplyMessages.Delete_messagebox_accept_text);
	}

	public static void ShowMessageCantDelete(Shell shell) {
		MessageDialog.openInformation(shell,
				JExpSupplyMessages.Delete_messagebox_title,
				JExpSupplyMessages.Delete_messagebox_cant_text);
	}
}
